package com.me.shop.user.action;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.me.shop.user.bean.User;
import com.me.shop.user.service.UserService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class UserAction extends ActionSupport implements ModelDriven<User> {
	
	private String checkCode;
	public void setCheckCode(String checkCode) {
		this.checkCode = checkCode;
	}

	private UserService userService;
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	private User user;
	public User getModel() {
		user = new User();
		return user;
	}
	
	public String registPage() {
		return "registPage";
	}
	
	public String findByName() throws IOException {
		User existUser = userService.findByUsername(user.getUsername());
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html;charset=UTF-8");
		if(existUser != null) {
			response.getWriter().print("<font color='red'>用户名已经存在</font>");
		} else {
			response.getWriter().print("<font color='green'>用户名可以使用</font>");
		}
		return NONE;
	}
	
	public String regist() {
		String checkCode1 = (String)ServletActionContext.getRequest().getSession().getAttribute("checkcode");
		if(!checkCode.equalsIgnoreCase(checkCode1)) {
			this.addActionError("验证码错误");
			return "checkCodeFail";
		}
		userService.save(user);
		this.addActionMessage("注册成功，请去邮箱激活");
		return "msg";
	}

	
	public String active() {
		User existUser = userService.findbyCode(user.getCode());
		if(existUser == null) {
			this.addActionMessage("验证失败：验证码错误");
		} else {
			existUser.setState(1);
			existUser.setCode(null);
			userService.update(existUser);
			this.addActionMessage("激活成功：登录即可购物");
		}
		return "msg";
	}

	public String loginPage() {
		return "loginPage";
	}
	
	public String login() {
		User existUser = userService.login(user);
		if(existUser == null) {
			this.addActionError("登录失败：可能是因为用户名或密码或账号还未激活");
			return "login";
		} else {
			ServletActionContext.getRequest().getSession().setAttribute("existUser", existUser);
			return "loginSuccess";
		}
	}
	
	public String quit() {
		ServletActionContext.getRequest().getSession().invalidate();
		return "quit";
	}
	
	
}
